/*
 自定义 collectionView 的无限轮播
 */

#import "headViewCollectionViewController.h"
#import "headViewCell.h"



@interface headViewCollectionViewController ()

/// 图片对象
@property (nonatomic, strong) NSArray *images;

/// 占位图片
@property (nonatomic, strong) UIImage *placeholder;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) UIPageControl *page;

@property (nonatomic, assign) CGRect frame;

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@end

@implementation headViewCollectionViewController

static NSString * const reuseIdentifier = @"Cell";


#pragma mark - 初始化方法

- (instancetype)initWithframe:(CGRect)frame images:(NSArray *)images placeholderImage:(UIImage *)placeholderImage {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.flowLayout = layout;

    CGFloat w = frame.size.width;
    
    CGFloat h = frame.size.height;
    
    layout.itemSize = CGSizeMake(w, h);

//    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//
//    layout.minimumInteritemSpacing = 0;
//    layout.minimumLineSpacing = 0;
    
    if (self = [super initWithCollectionViewLayout:layout]) {
    
        self.images = images;
        
        self.frame = frame;
        
        self.placeholder = placeholderImage;
        
        [self.view addSubview:self.page];
        
        /// 显示横线的线条
        self.collectionView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        
        [self.page mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.mas_equalTo(self.view);
            make.bottom.mas_equalTo(self.view.mas_bottom).offset(10);
            
        }];
    }
    return self;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.frame.size.width,self.frame.size.height);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.collectionView registerClass:[headViewCell class] forCellWithReuseIdentifier:reuseIdentifier];

    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:1 inSection:1];
    
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];

    [self addTimer];
  
}

- (void)viewDidLayoutSubviews {

    [super viewDidLayoutSubviews];
    [self setupFlowLayout];
}

-(void)setupFlowLayout{
//    self.flowLayout.itemSize = self.frame.size;
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.flowLayout.minimumInteritemSpacing = 0;
    self.flowLayout.minimumLineSpacing = 0;
    
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = YES;
    
}


#pragma mark - time的实现

// 添加定时器
- (void)addTimer{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
    
    self.timer=timer;
}
// 删除定时器
-(void)removeTimer{
    
    [self.timer invalidate];
    
    self.timer=nil;
}

// 释放timer
- (void)viewDidDisappear:(BOOL)animated
{
    [self removeTimer];
}
// 添加timer
- (void)viewDidAppear:(BOOL)animated
{
    if (!_timer) {
        [self addTimer];
    }
}


#pragma mark - scrollView 的代理方法
// 当用户开始拖拽的时候就调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeTimer];
}
// 当用户停止拖拽的时候调用
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self addTimer];
}
// 设置页码
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    int page = (int)(scrollView.contentOffset.x/scrollView.frame.size.width+0.5) % self.imageS.count;
    self.page.currentPage = page;
    
    //得到cell的索引
    NSInteger index = self.collectionView.contentOffset.x / self.collectionView.frame.size.width;
    
    //取模运算,得到每个section中新闻的索引
    index = index % self.images.count;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:1];
    
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:NO];
}




//- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView;{
//  
//    
//}



#pragma mark - Method
// 展示下一页
-(void)nextPage {
    
    //1）获取当前正在展示的位置
    NSIndexPath *currentIndexPath=[[self.collectionView indexPathsForVisibleItems] lastObject];
    
//    NSLog(@"%@",[self.collectionView indexPathsForVisibleItems]);
    
    //2）计算出下一个需要展示的位置
    
    NSInteger nextItem=currentIndexPath.item+1;
    
    
    NSInteger nextSection=currentIndexPath.section;
    
    
    
    if (nextItem==self.imageS.count) {
        nextItem=0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath=[NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    
    //3）通过动画滚动到下一个位置
    
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}


#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 3;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.images.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    headViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    cell.image = self.images[indexPath.item];
    
    cell.frame = self.frame;

    
    return cell;
}



#pragma mark - 懒加载控件

- (UIPageControl *)page {
    
    if (_page == nil) {
        _page = [[UIPageControl alloc] init];
//        _page.backgroundColor = [UIColor blackColor]; 
        _page.currentPageIndicatorTintColor = [UIColor blackColor];
        _page.pageIndicatorTintColor = [UIColor blueColor];
        _page.numberOfPages = self.images.count;
        _page.currentPage = 0;
    }
    return _page;
}


- (NSArray *)imageS {
    
    if (_images == nil) {
        
        
        _images = [NSArray array];
    }
    return _images;
}



@end
